package com.irssproject.app.dao.lectorRSS.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.irssproject.app.dao.lectorRSS.iface.LabelsDAO;
import com.irssproject.app.entitats.Label;

public class LabelsDAOHibernate extends HibernateDaoSupport implements LabelsDAO {

    @Override
    public Long insertLabel(Label label) {
        return (Long) getHibernateTemplate().save(label);
    }

    @Override
    public Label getEtiqueta(String nom) {
        return (Label) getHibernateTemplate().find("from Label et where et.nom = ?", nom);
    }

    @SuppressWarnings("unchecked")
    public List<Label> getListEtiquetes() {
        return (List<Label>) getHibernateTemplate().loadAll(Label.class);
    }

    public void deleteEtiqueta(Label etiqueta) {

        getHibernateTemplate().delete(etiqueta);
    }

    @SuppressWarnings("unchecked")
    public Label getLabelByName(String label) {
        List<Label> lstEt = new ArrayList<Label>();
        lstEt = (List<Label>) getHibernateTemplate().find("from Label where nom = ?", label);

        return (lstEt != null && lstEt.size() == 1 ? lstEt.get(0) : null);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Label> getListEtiquetesByIdUsuari(Integer idusuari) {

        return (List<Label>) getHibernateTemplate().find("from Label et join Subscription su on et.idetiqueta = su.idetiqueta join User us on us.idusuari = su.idusuari where us.idusuari = ?", idusuari);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Label> getEtiquetaLikeNom(String terme) {

        DetachedCriteria criteria = DetachedCriteria.forClass(Label.class);
        criteria.add(Restrictions.like("nom", "%" + terme + "%"));

        return getHibernateTemplate().findByCriteria(criteria);

    }
}
